package com.hdoit.ares.web.cust.controllers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.team.model.CooperationTeam;
import com.hdoit.ares.logical.team.service.ICooperationTeamService;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.logical.viewmodel.cust.CustomerStatistic;
import com.hdoit.ares.logical.viewmodel.cust.CustomerTree;
import com.hdoit.ares.selfcommon.utils.ExportExcel;
import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.component.export.excel.ExportModel;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.component.web.JsonActionResult;



/**
 * @author      chenghuan
 * @email       
 * @createtime  2017年10月27日 14:58:02
 * @comment
 */
@Controller
@RequestMapping(value = "/admin/cust/customer/")
public class CustomerController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/admin/cust/customer/";
    }

    private ICustomerService customerService;
    public ICustomerService getCustomerService() {
        return customerService;
    }
    @Resource
    public void setCustomerService(ICustomerService customerService) {
        this.customerService = customerService;
    }
    
    private ICooperationTeamService cooperationTeamService;
	public ICooperationTeamService getCooperationTeamService() {
		return cooperationTeamService;
	}
	@Resource
	public void setCooperationTeamService(ICooperationTeamService cooperationTeamService) {
		this.cooperationTeamService = cooperationTeamService;
	}

	private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="customerDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String exportExcelViewName = "exportExcel";
    private final String teamClassDetailedViewName="teamClassDetailed";
    
    
    @RequestMapping(value = exportExcelViewName, method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public String exportExcel(CustomerSearch customerSearch){
    	
	    List<Customer> customers = customerService.queryListMP(customerSearch);
		
		ExportModel em=new ExportModel();
		
		
		em.setExcelInfoCode(ExportExcel.AllCustomerInfo);
		
		em.setDataSource(customers);
		String cacheId=CommonUtils.getKeyId();
		cached.put(cacheId, em,60);
		
		return cacheId;
	}
    
    
    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,CustomerSearch search,boolean ajaxPost){
      
    	CooperationTeam cooperationTeam = cooperationTeamService.queryModel(getLoginModel().getLoginId());
    	if(cooperationTeam != null && !StringUtils.isEmpty(cooperationTeam.getCityId())){
    		search.setCityId(cooperationTeam.getCityId());
    	}
    	pagerModel.setTotalAmount(customerService.queryCountMP(search));
        List<Customer> customers= customerService.queryListMP(search,pagerModel);
        CustomerStatistic customerStatistic = customerService.queryModel(search);
        
       /* System.err.println("总人数\t" + customerStatistic.getTotal());
        System.err.println("高创人数\t" + customerStatistic.getHighMaker());
        System.err.println("初创人数\t" + customerStatistic.getMaker());
        System.err.println("会员人数\t" + customerStatistic.getVip());
        System.err.println("游客人数\t" + customerStatistic.getVisitor());*/
        
        model.addAttribute(ManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("customers", customers);
        model.addAttribute("customerSearch", search);
        model.addAttribute("customerStatistic", customerStatistic);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String customerDetailed(Model model,String key){
        Customer customer=new Customer();
        if(!StringUtils.isEmpty(key)){
            customer=customerService.queryModelMP(key);
        }
        model.addAttribute("customer", customer);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Customer customer){
        if(StringUtils.isEmpty(customer.getId())){
            customer.setId(CommonUtils.getKeyId());
            customer.setModelStatus(ModelStatus.add);
        }else{
            customer.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(customerService.applyChange(customer)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("customer", customer);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(customerService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    @RequestMapping(value = teamClassDetailedViewName, method = { RequestMethod.GET})
    public String teamClassDetailed(Model model,String key){
       
    	CustomerSearch searchList = new CustomerSearch();
        searchList.setRefereeId(key);
        List<CustomerTree> customerTrees = customerService.queryListForConsumption(searchList);
        if(customerTrees == null){
    		customerTrees = new ArrayList<CustomerTree>();
    	}
        //筛选出一代数排序
        List<CustomerTree> personAscs =  personAsc(customerTrees);
        List<CustomerTree> personDescs  = personDesc(customerTrees);
       
        //筛选出消费排序
        List<CustomerTree> moneyAscs= moneyAsc(customerTrees);
        List<CustomerTree> moneyDescs= moneyDesc(customerTrees);
        
        CustomerSearch searchModel = new CustomerSearch();
        searchModel.setId(key);
        
        CustomerTree customerTree = customerService.queryModelForConsumption(searchModel);
    	
    	/*System.err.println("到底有多长" + customerTrees.size());*/
        model.addAttribute("customerTrees", customerTrees);
        model.addAttribute("customerTree", customerTree);
        model.addAttribute("personAscs", personAscs);
        model.addAttribute("personDescs", personDescs);
        model.addAttribute("moneyAscs", moneyAscs);
        model.addAttribute("moneyDescs", moneyDescs);
        
        ActionResult actionResult = new ActionResult();
        actionResult.setRefresh(true);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(teamClassDetailedViewName);
    }
    
	private List<CustomerTree> moneyAsc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			customerTree.setSord(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).intValue());
			customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(i -1));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
		
	}
	private List<CustomerTree> moneyDesc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			customerTree.setSord(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).intValue());
			/*System.err.println(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());*/
			customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
			/*customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());*/
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(size -i));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
		
	}
	private List<CustomerTree> personAsc(List<CustomerTree> customerTrees) {
		
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			int num = customerTree.getFirstVisitor() + customerTree.getFirstVip() + customerTree.getFirstMaker() + customerTree.getFirstHighMaker();
			customerTree.setSord(num);
			customerTree.setTotalPerson(num);
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(i -1));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
	}
	private List<CustomerTree> personDesc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		
		for(CustomerTree customerTree:customerTrees){
			int num = customerTree.getFirstVisitor() + customerTree.getFirstVip() + customerTree.getFirstMaker() + customerTree.getFirstHighMaker();
			customerTree.setSord(num);
			customerTree.setTotalPerson(num);
		}
		
		Collections.sort(customerTrees);
		
		
		
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(size - i));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
	}
}